#include "widget.h"
#include "ui_widget.h"
extern "C"
{
#include "qrencode.h"
}
#include <QImage>
#include <QPainter>
#include <QColor>
#include <QPixmap>
#include <QDebug>



Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

QImage GenerateQRcode(QString tempstr, qint32 outWidth, qint32 outHeight)
{
    QImage outQrcodeImg;
    QRcode *qrcode = QRcode_encodeString(tempstr.toStdString().c_str(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);

    qInfo() << "outWidth  " << outWidth;
    qInfo() << "outHeight " << outHeight;

    qInfo() << "qrcode->width " << qrcode->width;
    qInfo() << "qrcode->height " << qrcode->width;

    qint32 qrcode_width = qrcode->width > 0 ? qrcode->width : 1;
    // 二维码图片的缩放比例
    double scale_x = (double)outWidth / (double)qrcode_width;
    double scale_y =(double) outHeight /(double) qrcode_width;

    outQrcodeImg = QImage(outWidth, outHeight, QImage::Format_ARGB32);

    QPainter painter(&outQrcodeImg);
    QColor background(Qt::white);
    QColor foreground(Qt::black);

    painter.setBrush(background);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, outWidth, outHeight);
    painter.setBrush(foreground);

    for( qint32 y = 0; y < qrcode_width; y ++)
    {
        for(qint32 x = 0; x < qrcode_width; x++)
        {
            unsigned char b = qrcode->data[y * qrcode_width + x];
            if(b & 0x01)
            {
                QRectF r(x * scale_x, y * scale_y, scale_x, scale_y);
                painter.drawRects(&r, 1);
            }
        }
    }

    return outQrcodeImg;
}

void Widget::on_pushButton_clicked()
{
    QString input = ui->textEdit->toPlainText();
    int w = ui->label->width();
    int h = ui->label->height();

    QImage img = GenerateQRcode(input, w, h);
    // img.save("001.png");
    ui->label->setPixmap(QPixmap::fromImage(img));
}

